We are implementing IEnumerator and IEnumerable in our class
static void Main(string[] args)
{
ParsingFile data = new ParsingFile();
foreach (var line in data) // Calls the current, the implicit type of line is object but we want is as a DataRow
{
//call MoveNext
}
}
public class ParsingFile : IEnumerator , IEnumerable
{
object IEnumerator.Current //need the object to be of type DataRow to avoid casting in foreach
{
//return a DataRow
}
public IEnumerator GetEnumerator()
{
return this;
}
public bool MoveNext()
{
//Do something
}
}
The return type of current is object but want to explicitly return DataRow. Please let us know what will be the approach to achieve this?
Quite honestly, unless you have very particular requirements, you're better off using an iterator block here, i.e. you just write:
public class ParsingFile : IEnumerable<DataRow>
{
// use an iterator block for the typed API
public IEnumerator<DataRow> GetEnumerator()
{
//Do something that involves, perhaps in a loop
// yield return someValue;
// and/or
// yield break;
}
// use explicit implementation for the untyped API
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
You absolutely can implement your own strong-typed enumerator, which may (although doesn't strictly need to) mean implementing IEnumerator<T>, but there are a lot of gotchas (such as allowing independent concurrent enumeration) that make it safer to let the compiler do the hard work.
Instead of implementing an IEnumerator, which it's interface specifies that current is an object, you have to implement IEnumerator<T>
public class ParsingFile : IEnumerator<DataRow>
{
public DataRow Current { get; }
// rest of code ommited for brevity
}
As mentioned by jon skeet, implement IEnumerable<DataRow> or IEnumerator<DataRow> instead.
I would suggest to never implement both IEnumerator and IEnumerable by the same class. Consider the following:
var myParsingFile = ...
var dr1 = myParsingFile.First();
var dr2 = myParsingFile.First();
In your case the dr1 and dr2 would be different objects, and that is just very confusing.
You may also lookinto iterator blocks for an easier way to make enumerators.